﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace hmi
{
    /// <summary>
    /// UdpOptionWindow.xaml 的交互逻辑
    /// </summary>
    public partial class UdpOptionWindow : Window
    {
        private static UdpOptionWindow instance;

        private UdpOptionWindow()
        {
            InitializeComponent();
        }

        public static UdpOptionWindow CreateWindow()
        {
            if (instance == null)
            {
                instance = new UdpOptionWindow();
            }
            return instance;
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            instance = null;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            DisplayInit();
            IPRefresh();
        }

        private void DisplayInit()
        {
            LocalPortTxt.Text = ConfigurationManager.AppSettings["LocalPort"];
            TargetIPTxt.Text = ConfigurationManager.AppSettings["TargetIP"];
            TargetPortTxt.Text = ConfigurationManager.AppSettings["TargetPort"];
            InitOpenBtn();
        }

        private void IPRefresh()//刷新可用IP
        {
            LocalIPCbobox.Items.Clear();

            string name = Dns.GetHostName();
            IPAddress[] ipadrlist = Dns.GetHostAddresses(name);
            List<string> localIPV4List = new List<string>();
            foreach (IPAddress ipa in ipadrlist)
            {
                if (ipa.AddressFamily == AddressFamily.InterNetwork)
                {
                    var ipStr = ipa.ToString();
                    LocalIPCbobox.Items.Add(ipStr);//下拉控件里添加可用IP
                    localIPV4List.Add(ipStr);
                }
            }
            if (localIPV4List.Count > 0)
            {
                string localIPStr = ConfigurationManager.AppSettings["LocalIP"];
                if (localIPStr == "" || !localIPV4List.Contains(localIPStr))
                {
                    LocalIPCbobox.SelectedIndex = 0;//没有IP存储值或者当前可选IP中未包含存储值,默认选取可选的第一个串口
                }
                else
                {
                    LocalIPCbobox.Text = localIPStr;
                }
            }
            else
            {
                MessageBox.Show("无可用网络");
            }
        }      

        private void InitOpenBtn()
        {
            if (CommManage.Instance.CommTool.IsOpen)
            {
                OpenBtn.Content = "关闭";
                OpenImage.Source = new BitmapImage(new Uri("image\\On.png", UriKind.Relative));//开关状态图片切换为ON
            }
            else
            {
                OpenBtn.Content = "打开";
                OpenImage.Source = new BitmapImage(new Uri("image\\Off.png", UriKind.Relative));//开关状态图片切换为off
            }
        }

        private void OpenBtn_Click(object sender, RoutedEventArgs e)
        {
            if (!(CommManage.Instance.IsUdp))
            {
                return;
            }
            if ((string)OpenBtn.Content == "打开")
            {
                string name = Dns.GetHostName();
                IPAddress[] ipadrlist = Dns.GetHostAddresses(name);
                List<string> localIPV4List = new List<string>();
                foreach (IPAddress ipa in ipadrlist)
                {
                    if (ipa.AddressFamily == AddressFamily.InterNetwork)
                    {
                        var ipStr = ipa.ToString();
                        LocalIPCbobox.Items.Add(ipStr);//下拉控件里添加可用IP
                        localIPV4List.Add(ipStr);
                    }
                }
                if (localIPV4List.Count <= 0)
                {
                    MessageBox.Show("无可用网络");
                    IPRefresh();
                    return;
                }
                if (localIPV4List.Contains(LocalIPCbobox.Text) == false)
                {
                    MessageBox.Show("当前选择网络已经断开连接");
                    IPRefresh();
                    return;
                }
                SetPara();
                CommManage.Instance.CommTool.Open();
                if (!CommManage.Instance.CommTool.IsCommRight)
                {
                    MessageBox.Show(((UdpComm)(CommManage.Instance.CommTool)).LocalIPEndPoint.Address.ToString() + "的端口" + ((UdpComm)(CommManage.Instance.CommTool)).LocalIPEndPoint.Port + "无法打开！请检查此端口是否有效或被占用！");
                    return;
                }                
                SaveLocalConfigure();
                OpenBtn.Content = "关闭";
                OpenImage.Source = new BitmapImage(new Uri("image\\On.png", UriKind.Relative));//开关状态图片切换为ON
            }
            else if ((string)OpenBtn.Content == "关闭")
            {
                CommManage.Instance.CommTool.Close();                            
                OpenBtn.Content = "打开";
                OpenImage.Source = new BitmapImage(new Uri("image\\Off.png", UriKind.Relative));//开关状态图片切换为off  
            }
        }

        private void SetPara()
        {
            IPAddress localIP = IPAddress.Parse(LocalIPCbobox.Text.ToString());
            int localPort = Convert.ToInt32(LocalPortTxt.Text);
            ((UdpComm)(CommManage.Instance.CommTool)).LocalIPEndPoint = new IPEndPoint(localIP, localPort);
        }        

        private void TargetSetBtn_Click(object sender, RoutedEventArgs e)
        {
            IPAddress targetIP = IPAddress.Parse(TargetIPTxt.Text.ToString());;
            int targetPort = Convert.ToInt32(TargetPortTxt.Text);
            ((UdpComm)(CommManage.Instance.CommTool)).TargetIPEndPoint = new IPEndPoint(targetIP, targetPort);
            SaveTargetConfigure();
        }

        private void SaveLocalConfigure()
        {
            Configuration configure = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            configure.AppSettings.Settings["LocalIP"].Value = LocalIPCbobox.Text;
            configure.AppSettings.Settings["LocalPort"].Value = LocalPortTxt.Text;
            configure.Save();
            ConfigurationManager.RefreshSection("appSettings");
        }

        private void SaveTargetConfigure()
        {
            Configuration configure = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            configure.AppSettings.Settings["TargetIP"].Value = TargetIPTxt.Text;
            configure.AppSettings.Settings["TargetPort"].Value = TargetPortTxt.Text;
            configure.Save();
            ConfigurationManager.RefreshSection("appSettings");
        }

        private void LocalPortTxt_KeyDown(object sender, KeyEventArgs e)
        {
            OnlyNum(e);
        }

        private void TargetPortTxt_KeyDown(object sender, KeyEventArgs e)
        {
            OnlyNum(e);
        }

        private void OnlyNum(KeyEventArgs e)
        {
            //屏蔽非法按键
            if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
            {
                e.Handled = false;
            }
            else if ((e.Key >= Key.D0 && e.Key <= Key.D9))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }
    }
}
